package com.thz.houserental.infrastructure.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thz.houserental.infrastructure.exception.ParameterException;
import com.thz.houserental.infrastructure.table.Dict;
import com.thz.houserental.infrastructure.table.DictData;
import com.thz.houserental.infrastructure.web.mapper.DictDataMapper;
import com.thz.houserental.infrastructure.web.service.DictDataService;
import com.thz.houserental.infrastructure.web.service.DictService;
import com.thz.houserental.infrastructure.web.vo.DictDataInfo;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictDataServiceImpl  extends ServiceImpl<DictDataMapper, DictData> implements DictDataService {

    private final DictDataMapper dictDataMapper;
    private final DictService dictService;

    public DictDataServiceImpl(DictDataMapper dictDataMapper, DictService dictService) {
        this.dictDataMapper = dictDataMapper;
        this.dictService = dictService;
    }

    @Override
    public void checkByCodeAndKey(String dictCode, String dictKey) {
        // 1. 检验dictCode是否存在
        Integer dictCount = dictService.lambdaQuery().eq(Dict::getDictCode, dictCode).count();
        if(dictCount == 0) {
            throw new ParameterException(10500);
        }
        // 2. 检验是否有重复key, value
        Integer dataCount = this.lambdaQuery()
                .eq(StrUtil.isNotBlank(dictCode), DictData::getDictCode, dictCode)
                .eq(StrUtil.isNotBlank(dictKey), DictData::getDictKey, dictKey)
                .count();
        if(dataCount != 0) {
            throw new ParameterException(10500);
        }
    }

    @Override
    public DictDataInfo getDictDataInfo(String dictId) {
        Dict dict = this.dictService.getById(dictId);
        List<DictData> dictData = this.lambdaQuery()
                .eq(DictData::getDictCode, dict.getDictCode())
                .list();
        
        return DictDataInfo.builder()
                .dict(dict)
                .dictData(dictData)
                .build();
    }
}
